package com.example.yanzhengma125.demos;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
@RequestMapping("/admin")
@RestController
public class KaptchaController {
    private static final String KAPTCHA_SESSION_KEY = "ADMIN_KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "ADMIN_KAPTCHA_SESSION_DATE";
    private static final long TIME_OUT = 60*1000;//一分钟, 毫秒数
    @RequestMapping("/check")
    public boolean check(String inputCaptcha, HttpSession session){
        if (!StringUtils.hasLength(inputCaptcha)){
            return false;
        }
        System.out.println(inputCaptcha);
        //生成的验证码(正确的验证码)
        String saveCaptcha = (String)session.getAttribute(KAPTCHA_SESSION_KEY);
        Date savaCaptchaDate = (Date)session.getAttribute(KAPTCHA_SESSION_DATE);
        System.out.println(saveCaptcha);
        if (inputCaptcha.equalsIgnoreCase(saveCaptcha)){//不区分大小写
            if (savaCaptchaDate!=null || System.currentTimeMillis()-savaCaptchaDate.getTime()<TIME_OUT){
                return true;
            }
        }
        return false;
    }
}
